<script setup>
import SkuPopup from './components/SkuPopup.vue'
import ProductDetailsSkeleton from './components/ProductDetailsSkeleton.vue'
import { uniFetch } from '../../api/uni-fetch';
import { onLoad } from '@dcloudio/uni-app';
import { ref, onMounted } from 'vue'
import { onShareAppMessage } from '@dcloudio/uni-app'
import { useUserStore } from "/store/user.js"

const store = useUserStore()

onLoad((e) => {
	if (e?.invite_token) {
		//将推荐人的openid存储
		uni.setStorageSync("invite_token", e.invite_token);
	}
});

// 正在加载
const isLoading = ref(false)
const goods = ref({ member_price: 0, old_price: 0, product_detail: { description: '' }, detail_image: [''] })
// 购物车总数量
const cartTotal = ref(0)
// 当前商品ID
const { goodsId, groudId, group_price } = defineProps(['goodsId', 'groudId', 'group_price'])

// 销售数量
const soldCount = ref(0)
// 生成或获取销售数量
function getOrCreateSoldCount() {
  // 从缓存获取
  const cachedCount = uni.getStorageSync(`sold_${goodsId}`)
  if (cachedCount) {
    // 每次增加1-3个
    const increment = Math.floor(Math.random() * 3) + 1
    soldCount.value = cachedCount + increment
  } else {
    // 首次生成96-400之间的随机数
    soldCount.value = Math.floor(Math.random() * (400 - 96 + 1)) + 96
  }
  // 更新缓存
  uni.setStorageSync(`sold_${goodsId}`, soldCount.value)
}
onMounted(() => {
  getOrCreateSoldCount()
})

async function getGoodsInfo() {
	const res = await uniFetch.post('/product/detail', {
		app_id: uni.appId,
		id: goodsId
	})
	if (res.code === 10000) {
		// Object.assign(goods, res.data)
		res.data.product_detail.description = res.data.product_detail.description.replace(/width:\d+px/gi,
			'width:100%')
		isLoading.value = true
		goods.value = res.data
		isCreat.value = true
	}
}

function onPreviewImages(index) {
	const previewUrl = []
	goods.value.detail_image.forEach(item => {
		previewUrl.push('https://' + item)
	})

	uni.previewImage({
		current: index,
		urls: previewUrl
	})
}

const currIndex = ref(0)

function handleChange(e) {
	currIndex.value = e.detail.current
}
getGoodsInfo()



/**
 * 显示/隐藏SKU弹窗
 * @param {skuMode} 模式 1:都显示 2:只显示购物车 3:只显示立即购买
 */

const skuPopup = ref(null)
const isCreat = ref(false)
// 模式 1:都显示 2:只显示购物车 3:只显示立即购买
function onShowSkuPopup(mode = 1) {
	skuPopup.value.openPop(mode)
}

// 跳转到首页
function onTargetHome(e) {
	uni.switchTab({
		url: '/pages/index/index'
	})
}

// 跳转到购物车页
function onTargetCart() {
	uni.switchTab({
		url: '/pages/ShoppingCart/ShoppingCart'
	})
}


/**
 * 分享当前页面
 */
onShareAppMessage(() => {
	// console.log(uni.appId, 'appId');
	uniFetch.post("/user-member/share", {
		app_id: uni.appId
	}).then(async res => {
		// console.log("分享返回", res)
		if (res.code === 10000) {
			// uni.setStorageSync('user', res.data)
		} else {
			uni.showToast({
				title: res.message || '分享失败',
				icon: 'none',
				duration: 2000
			})
			await new Promise(resolve => setTimeout(resolve, 2000)) 
		}
	})
	const openid = uni.getStorageSync("userLoginCode").openid || uni.getStorageSync("userLoginCode").user.openid
	// console.log(openid, 'openid');
	return {
		title: '华靓甄选',
		path: '/pages/ProductDetails/ProductDetails?goodsId=' + goodsId + "&invite_token=" + openid
	}
})
</script>

<template>
	<view v-if="isLoading" class="container">
		<!-- 商品图片轮播 -->
		<view class="images-swiper">
			<swiper indicator-active-color="#4e0072" class="swiper-box" autoplay :duration="800" indicator-dots
				:interval="4000" :circular="true" @change="handleChange" :current="currIndex">
				<!-- 轮播图片 -->
				<swiper-item v-for="(item, index) in goods.detail_image" :key="item" @click="onPreviewImages(index)">
					<view :class="['slide-image', index == currIndex ? 'active' : '']">
						<image mode="scaleToFill" :src="item"></image>
					</view>
				</swiper-item>
			</swiper>
		</view>

		<!-- <SlideImage v-if="!isLoading" :images="goods.detail_image" /> -->

		<!-- 商品信息 -->
		<view class="goods-info ">
			<!-- 价格、销量 -->
			<view class="info-item__top ">
				<view class="block-left  ">
					<!-- 商品售价 -->
					<text class="floor-price__samll" v-if="!groudId">专属价:￥
						<text class="floor-price" v-if="store.memberInfo.is_member">{{ goods.member_price.toFixed(2) }}</text>
						<text class="floor-price" v-else>{{ goods.price.toFixed(2) }}</text>
					</text>
					<text class="floor-price__samll" v-else>
						团购价:￥
						<text class="floor-price">{{ (group_price - 0).toFixed(2) }}</text>
					</text>
					

					<view style="display: flex; justify-content: space-between;">
						<view class="original-price">￥{{ goods.old_price.toFixed(2) }}</view>
						<view class="original-ys">已售{{ soldCount }}件</view>
					</view>
				</view>

			</view>
			<!-- 标题、分享 -->
			<view class="info-item__name">
				<view class="goods-name flex-box">
					<text class="twoline-hide">{{ goods.title }}</text>
					<view class="desribe">
						{{ goods.sub_title }}
					</view>
				</view>

				<view class="goods-share__line"></view>
				<view class="goods-share">
					<button class="share-btn flex-dir-column" open-type="share">
						<uni-icons custom-prefix="iconfont" type="icon-fenxiang" color="#000" size="20"></uni-icons>
						<view class="f-24">分享</view>
					</button>
				</view>

			</view>

		</view>

		<!-- 选择商品规格 -->
		<view class="goods-choice  " @click="onShowSkuPopup(2)" v-if="!groudId">
			<view class="spec-list">
				<view class="flex-box">
					<text class="col-8">选择：</text>
					<text class="spec-name">规格</text>
				</view>
				<view>
					<uni-icons type="right" color="#3d3d3d" size="20"></uni-icons>
				</view>
			</view>
		</view>

	
		<SkuPopup ref="skuPopup" :goods="goods" :groudId="groudId" :group_price="group_price" v-if="isCreat">
		</SkuPopup>

		<!-- 评价 -->
		<!-- <Comment v-if="!isLoading" :goods-id="goodsId" :limit="2" /> -->

		<!-- 商品描述 -->
		<view class="detial">
			<view class="detial-top">
				<view class="detial-top-left"></view>
				<view class="detial-top-text">图文详情</view>
				<view class="detial-top-left"></view>
			</view>

			<view class="detial-item">
				<view class="detial-item-top" v-if="true">
					<view v-html="goods.product_detail.description"></view>
				</view>
				<view class="item-empty " v-else> 暂无描述 </view>
			</view>
		</view>


		<!-- 底部选项卡 -->
		<view class="footer-fixed">
			<view class="footer-container">
				<!-- 导航图标 -->
				<view class="foo-item-fast">
					<!-- 首页 -->
					<view class="fast-item fast-item--home" @click="onTargetHome">
						<view class="fast-icon">
							<uni-icons custom-prefix="iconfont" type="icon-31shouye" color="#000" size="20"></uni-icons>
						</view>
						<view class="fast-text">
							<text>首页</text>
						</view>
					</view>

					<!-- 客服  -->
					<button class="btn-normal" open-type="contact">
						<view class="fast-item">
							<view class="fast-icon">
								<uni-icons custom-prefix="iconfont" type="icon-kefu" color="#000" size="20"></uni-icons>
							</view>
							<view class="fast-text">
								<text>客服</text>
							</view>
						</view>
					</button>

					<!-- 购物车 -->
					<view class="fast-item fast-item--cart" @click="onTargetCart" v-if="!groudId">
						<view v-if="cartTotal > 0" class="fast-badge fast-badge--fixed">
							{{ cartTotal > 99 ? '99+' : cartTotal }}
						</view>
						<view class="fast-icon">
							<uni-icons custom-prefix="iconfont" type="icon-gouwuche1" color="#000" size="20"></uni-icons>
						</view>
						<view class="fast-text">
							<text>购物车</text>
						</view>
					</view>
				</view>
				<!-- 操作按钮 -->
				<view class="foo-item-btn">
					<view class="btn-wrapper">
						<view v-if="!groudId" class="btn-item btn-item-deputy" @click="onShowSkuPopup(2)">
							<text>加入购物车</text>
						</view>
						<view class="btn-item btn-item-main" @click="onShowSkuPopup(1)">
							<text>立即购买</text>
						</view>
					</view>
				</view>
			</view>
		</view>
	</view>
	<ProductDetailsSkeleton v-else></ProductDetailsSkeleton>
</template>


<style lang="scss">
page {
	background: #fafafa;
}
</style>
<style lang="scss">
@import "@/static/iconfont/iconfont.css";

.images-swiper {
	width: 100%;
	height: 615rpx;
	background-color: #f3f3f3;
	display: flex;
	flex-direction: column;
	justify-content: flex-start;
	align-items: center;

}

.swiper-box {
	width: 100%;
	height: 615rpx;

	// 图片轮播
	.slide-image {
		padding-top: 10rpx;
		border-radius: 15rpx;
		width: 100%;
		height: 625rpx;
		text-align: center;
		transform: scale(0.8);
		transition: all 0.5s ease-in-out;

		&.active {
			transform: scale(1);
		}

		image {
			height: 560rpx;
			width: 560rpx;
			border-radius: 15rpx;
		}
	}
}


// @import "./detail.scss";
// 商品信息
.goods-info {
	background: #fff;
	padding: 25rpx 30rpx;
}

.info-item__top {
	min-height: 40rpx;
	margin-bottom: 20rpx;
	line-height: 1;
}

.floor-price__samll {
	font-size: 30rpx;
	line-height: 1;
	color: $custom-theme-color;
	margin-bottom: 10rpx;
}

// 商品价
.floor-price {
	color: $custom-theme-color;
	margin-right: 15rpx;
	margin-bottom: 15px;
	font-size: 48rpx;
	font-weight: 700;
}

.original-price {
	font-size: 26rpx;
	text-decoration: line-through;
	color: #959595;
	margin-right: 15rpx;
	margin-top: 10rpx;
}

.original-ys {
	font-size: 28rpx;
	color: #6d6868;
}

// 会员价标签
.user-grade {
	background: #3c3c3c;
	border-radius: 6rpx;
	padding: 8rpx 14rpx;
	margin-right: 15rpx;
	font-size: 24rpx;
	color: #EEE0C3;
}

.goods-sales {
	font-size: 24rpx;
	color: #959595;
}

.info-item__name {
	display: flex;
	align-items: center;
	background-color: #fff;
	// border-bottom: #f6f6f6 1rpx solid;
}

.goods-name {
	color: #000;
	font-size: 37rpx;
	width: 80%;
	overflow: hidden;
	line-height: 45rpx;
	min-height: 90rpx;
	box-sizing: border-box;

	.twoline-hide {
		display: -webkit-box;
		-webkit-line-clamp: 2;
		-webkit-box-orient: vertical;
		overflow: hidden;
		text-overflow: ellipsis;
	}

	.desribe {
		font-size: 23rpx;
		color: $custom-theme-red;
		line-height: 45rpx;
	}
}

/* 商品分享 */

.goods-share__line {
	border-left: 1rpx solid #f4f4f4;
	height: 80rpx;
	margin: 0 30rpx;
}

.goods-share .share-btn {
	line-height: normal;
	padding: 0;
	background: none;
	box-shadow: none;
	font-size: 25rpx;
	border: none;
	color: #191919;
}

.goods-share .share-btn::after {
	border: none;
}

.goods-share .share__icon {
	height: 30rpx;
	margin-bottom: 5rpx;
}

// 商品卖点
.info-item_selling-point {
	margin-top: 8rpx;
	font-size: 24rpx;
	color: #808080;
}

// 选择商品规格
.goods-choice {
	margin-top: 20rpx;
	padding: 26rpx 30rpx;
	font-size: 28rpx;
	background-color: #fff;

	.spec-list {
		display: flex;
		align-items: center;
		justify-content: space-between;

		.spec-name {
			margin-right: 10rpx;
		}
	}
}

// 商品详情
.item-title {
	padding: 26rpx 30rpx;
	min-height: 50rpx;
	width: 100%;
	display: flex;
	justify-content: center;
	align-items: center;
	font-size: 32rpx;
}


.detial {
	margin: 36rpx 0;
	display: flex;
	justify-content: center;
	align-items: center;
	flex-direction: column;
	background-color: #fff;

	.detial-top {
		width: 100%;
		height: 100rpx;
		display: flex;
		justify-content: center;
		align-items: center;

		.detial-top-text {
			font-size: 30rpx;
		}

		.detial-top-left {
			width: 100rpx;
			border: 1px solid #CFCECE;
			margin-left: 20rpx;
			margin-right: 20rpx;
		}
	}

	.detial-item {
		margin: 0 auto;
		width: 96%;
		display: flex;
		justify-content: center;
		align-items: center;

		.detial-item-top {
			width: 100%;
			display: flex;
			justify-content: center;
			align-items: center;

			rich-text {
				width: 100% !important;
				height: 100% !important;
				display: flex;
				justify-content: center;
				align-items: center;

				.fwb-img {
					width: 50rpx !important;
					height: 100% !important;
				}
			}
		}
	}
}

.item-empty {
	padding: 0rpx 30rpx 50rpx;
	font-size: 28rpx;
	min-height: 200rpx;
	line-height: 200rpx;
}

// 底部操作栏
.footer-fixed {
	position: fixed;
	bottom: var(--window-bottom);
	left: 0;
	right: 0;
	display: flex;
	z-index: 11;
	box-shadow: 0 -4rpx 40rpx 0 rgba(151, 151, 151, 0.24);
	background: #fff;

	// 设置ios刘海屏底部横线安全区域
	padding-bottom: constant(safe-area-inset-bottom);
	padding-bottom: env(safe-area-inset-bottom);
}

.footer-container {
	width: 100%;
	display: flex;
	height: 106rpx;
}

// 快捷菜单
.foo-item-fast {
	box-sizing: border-box;
	min-width: 214rpx;
	line-height: 1;
	display: flex;
	align-items: center;
	justify-content: space-evenly;
	margin-right: 12rpx;

	button.btn-normal {
		padding: 4rpx 0;
		text-align: center;
		background-color: #fff;
		width: 84rpx;

		&:after {
			border: none;
		}
	}

	.fast-item {
		position: relative;
		padding: 4rpx 0;
		line-height: 1;
		text-align: center;
		width: 84rpx;

		&--cart {
			margin-left: 6rpx;

			.fast-icon {
				margin-left: -12rpx;
			}
		}

		// 角标
		.fast-badge {
			display: inline-block;
			box-sizing: border-box;
			min-width: 16px;
			padding: 0 3px;
			color: #fff;
			font-weight: 500;
			font-size: 12px;
			font-family: -apple-system-font, Helvetica Neue, Arial, sans-serif;
			line-height: 1.2;
			text-align: center;
			background-color: #ee0a24;
			border: 1px solid #fff;
			border-radius: 999px;
		}

		.fast-badge--fixed {
			position: absolute;
			top: 0;
			right: 0;
			transform-origin: 100%
		}

		.fast-icon {
			font-size: 44rpx;
			margin-bottom: 8rpx;
		}

		.fast-text {
			font-size: 22rpx;
		}
	}
}

// 操作按钮
.foo-item-btn {
	flex: 1;

	.btn-wrapper {
		height: 100%;
		display: flex;
		align-items: center;
	}

	.btn-item {
		flex: 1;
		font-size: 28rpx;
		height: 72rpx;
		margin-right: 16rpx;
		color: #fff;
		border-radius: 50rpx;
		display: flex;
		justify-content: center;
		align-items: center;
	}

	// 立即购买按钮
	.btn-item-main {
		background: generate-gradient($custom-theme-color, $custom-theme-color-l)
	}

	// 购物车按钮
	.btn-item-deputy {
		background: linear-gradient(to right, #ffa600, #ffbb00);
	}
}
</style>